<template>
  <div class="tech-forum">
    <NavBar />

    <main class="forum-main">
      <div class="main-container">
        <div class="tag-info">
          <h2>{{ boardName }}</h2>
          <p>{{ description }}</p>
        </div>

        <div class="postList">
          <div v-if="posts.length === 0" class="empty-post">
            暂无技术问题，欢迎踊跃参与互动~
          </div>
          <div class="postItem" v-for="post in posts" :key="post.postId" v-else @click="goToPostDetail(post.postId)">
            <div class="stats" @click.stop>
              <div class="votes">
                <span class="count">{{ post.visitCount }}</span>
                <span>浏览量</span>
              </div>
              <div class="answers" :class="{ answered: post.replyCount > 0 }">
                <span class="count">{{ post.replyCount }}</span>
                <span>回答量</span>
              </div>
              <div class="views">
                <span class="count">{{ post.likeCount }}</span>
                <span>点赞量</span>
              </div>
            </div>
            <div class="content">
              <h3 class="title">
                <router-link :to="`/forum/detail/${post.postId}`">{{ post.postTitle }}</router-link>
              </h3>
              <div class="excerpt">{{ post.postContent }}</div>
              <div class="meta">
                <div class="user-info">
                  <span class="time">{{ formatTime(post.time) }}</span>
                  <router-link 
                    :to="{ path: '/forum/profile', query: { userId: post.userId } }" 
                    class="user" 
                    @click.stop
                  >
                    <img :src="post.profilePicture || defaultAvatar" alt="用户头像">
                    {{ post.nickName }}
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页控件 -->
        <el-pagination 
          background 
          size="small" 
          layout="total, sizes, prev, pager, next, jumper"
          :total="total" 
          v-model:current-page="params.pageNum" 
          v-model:page-size="params.pageSize"
          :page-sizes="[5, 10, 15, 20]" 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
        />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import NavBar from '@/components/NavBar.vue'
import { getTagInfoService, getPostsByTagService } from '@/apis/tag'
import { formatTime } from '@/utils/date' // 修正后的导入路径
import { reactive } from "vue";

// 默认头像
const defaultAvatar = ref('@/assets/images/avatar01.png')

// 路由参数
const route = useRoute()
const boardId = route.query.tagId

// 数据定义
const boardName = ref('')
const description = ref('')
const posts = ref([])
const total = ref(0)

const params = reactive({
  pageNum: 1,
  pageSize: 10
})

// 方法定义
const goToPostDetail = (postId) => {
  router.push(`/forum/detail/${postId}`)
}

const handleSizeChange = (newSize) => {
  params.pageSize = newSize
  params.pageNum = 1
  fetchPosts()
}

const handleCurrentChange = (newPage) => {
  params.pageNum = newPage
  fetchPosts()
}

const fetchTagInfo = async () => {
  try {
    const { boardName: name, description: desc } = await getTagInfoService({ boardId })
    boardName.value = name
    description.value = desc
  } catch (error) {
    ElMessage.error('获取标签信息失败')
  }
}

const fetchPosts = async () => {
  try {
    const res = await getPostsByTagService({ 
      boardId,
      pageNum: params.pageNum,
      pageSize: params.pageSize
    })
    
    posts.value = res.rows.map(post => ({
      ...post,
      // 修正为使用正确的标题字段
      postTitle: post.postTitle, 
      postContent: post.postContent,
      profilePicture: post.profilePicture || defaultAvatar.value
    }))
    
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  }
}

// 初始化
onMounted(() => {
  fetchTagInfo()
  fetchPosts()
})
</script>

<style scoped lang="scss">
.tech-forum {
  font-family: 'Segoe UI', Arial, sans-serif;
  color: #333;
  background: #f5f7fa;
  min-height: 100vh;
}

.forum-main {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.tag-info {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #eee;
  padding: 20px;
  margin-bottom: 24px;

  h2 {
    margin: 0 0 8px 0;
    font-size: 24px;
    color: #333;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 15px;
    line-height: 1.6;
  }
}

/* 复用主论坛的帖子列表样式 */
.postList {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #eee;
  padding: 16px;

  .empty-post {
    padding: 40px 20px;
    text-align: center;
    color: #999;
  }

  .postItem {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    gap: 20px;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    .stats {
      width: 90px;
      text-align: center;
      flex-shrink: 0;

      >div {
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .count {
          font-weight: bold;
          display: block;
          font-size: 18px;
        }

        span:last-child {
          font-size: 12px;
          color: #999;
        }

        &.answers.answered {
          color: #28a745;
        }
      }
    }

    .content {
      flex: 1;

      .title {
        margin: 0 0 8px 0;
        font-size: 18px;

        a {
          color: #333;
          text-decoration: none;

          &:hover {
            color: #007bff;
          }
        }
      }

      .excerpt {
        color: #666;
        margin: 8px 0 12px;
        font-size: 14px;
        line-height: 1.6;
      }

      .meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .user-info {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #999;
          font-size: 13px;

          .user {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #666;
            text-decoration: none;

            img {
              width: 24px;
              height: 24px;
              border-radius: 50%;
              object-fit: cover;
            }

            &:hover {
              color: #007bff;
            }
          }
        }
      }
    }
  }
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>